# -*- coding: UTF-8 -*-

import datetime

from sqlalchemy import and_

from app import db

__all__ = ['MonitorMetrics']


class MonitorMetrics(db.Model):
    '''
    監控指標數據
    '''
    __tablename__ = "monitor_metrics"
    mid = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='监控ID')
    item = db.Column(db.VARCHAR(80), nullable=False, comment='指标名称')
    value = db.Column(db.BigInteger, nullable=False, comment='指标数值')
    create_time = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now, comment='数据创建时间')

    __table_args__ = (
        db.Index('idx_moniter_metrics_item', 'item', unique=False),
        db.Index('idx_moniter_metrics_item_create_time', 'item', 'create_time', unique=False),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True
        }
    )

    def __repr__(self):
        return "<item='{}',value='{}',create_time='{}'>".format(self.item, self.value, self.create_time)

    @classmethod
    def get_item_data(cls, item, start_datatime, end_datatime):
        return db.session.query(cls) \
            .filter(and_(cls.item == item,
                         cls.create_time.between(start_datatime, end_datatime))) \
            .order_by(cls.create_time.asc()).to_dict()
